package com.dxb.webflux.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * ClassName：com.dxb.webflux.controller.WebFluxCompareController <br>
 * Description：TODO <br>
 *
 * @author 戴晓波 <br>
 * Date 2021/12/3/003 16:49 <br>
 * @version v1.0 <br>
 */
@RestController
@Slf4j
public class WebFluxCompareController {
    /**
     * Title：createStr <br>
     * Description：阻塞5秒钟 <br>
     * author：戴晓波 <br>
     * date：2021/12/3/003 16:51 <br>
     * <br>
     *
     * @return <br>
     */
    private String createStr() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
        }
        return "some string";
    }

    /**
     * Description：普通的SpringMVC方法 <br>
     * author：戴晓波 <br>
     * date：2021/12/3/003 16:52 <br>
     * <br>
     *
     * @return <br>
     */
    @GetMapping("/1")
    private String get1() {
        log.info("get1 start");
        String result = createStr();
        log.info("get1 end.");
        return result;
    }

    /**
     * Description：WebFlux(返回的是Mono) <br>
     * author：戴晓波 <br>
     * date：2021/12/3/003 16:53 <br>
     * <br>
     *
     * @return <br>
     */
    @GetMapping("/2")
    private Mono<String> get2() {
        log.info("get2 start");
        Mono<String> result = Mono.fromSupplier(() -> createStr());
        log.info("get2 end.");
        return result;
    }

    /**
     * Flux : 返回0-n个元素
     * 注：需要指定MediaType
     *
     * @return
     */
    @GetMapping(value = "/3", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    private Flux<String> flux() {
        return Flux.interval(Duration.ofSeconds(1))
                .onBackpressureDrop()
                .map(i -> "interval" + i);
    }

}
